import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi } from '@/api/auth'
import { userApi } from '@/api/user'
import type { User, LoginForm, RegisterForm } from '@/types'
import { UserRole } from '@/types'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref<string | null>(localStorage.getItem('token'))
  const user = ref<User | null>(null)
  const loading = ref(false)

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const isAdmin = computed(() => user.value?.role === UserRole.ADMIN)
  const isTeacher = computed(() => user.value?.role === UserRole.TEACHER || isAdmin.value)
  const isStudent = computed(() => user.value?.role === UserRole.STUDENT)

  // 设置Token
  const setToken = (newToken: string) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 清除Token
  const clearToken = () => {
    token.value = null
    localStorage.removeItem('token')
  }

  // 设置用户信息
  const setUser = (userData: User) => {
    user.value = userData
  }

  const setUerAvatar = async (avatar: string) => {
    if (user.value) {
      user.value.avatar_url = avatar
      await userApi.getUserAvatar(user.value.id)
    }
  }

  // 清除用户信息
  const clearUser = () => {
    user.value = null
  }

  // 登录
  const login = async (loginForm: LoginForm) => {
    try {
      loading.value = true
      const response = await authApi.login(loginForm)
      
      if (response.data) {
        setToken(response.data.token)
        setUser(response.data.user)
        return { success: true, message: '登录成功' }
      } else {
        return { success: false, message: '登录失败' }
      }
    } catch (error: any) {
      console.error('Login error:', error)
      return { success: false, message: error.message || '登录失败，请检查网络连接' }
    } finally {
      loading.value = false
    }
  }

  // 注册
  const register = async (registerForm: RegisterForm) => {
    try {
      loading.value = true
      const response = await authApi.register(registerForm)
      
      if (response.data) {
        setToken(response.data.token)
        setUser(response.data.user)
        return { success: true, message: '注册成功' }
      } else {
        return { success: false, message: '注册失败' }
      }
    } catch (error: any) {
      console.error('Register error:', error)
      return { success: false, message: error.message || '注册失败，请检查网络连接' }
    } finally {
      loading.value = false
    }
  }

  // 登出
  const logout = async () => {
    try {
      // 调用后端登出接口
      if (token.value) {
        await authApi.logout()
      }
    } catch (error) {
      console.error('Logout error:', error)
    } finally {
      // 无论是否成功，都清除本地状态
      clearToken()
      clearUser()
    }
  }

  // 检查登录状态
  const checkLogin = async () => {
    if (!token.value) {
      return false
    }

    try {
      const response = await authApi.checkLogin()
      
      if (response.data && response.data.is_logged_in) {
        // 如果没有用户信息，从响应中构建
        if (!user.value && response.data.user_id) {
          const userData = {
            id: response.data.user_id,
            username: response.data.username || '',
            email: response.data.email || '',
            avatar_url: response.data.avatar_url || '',
            role: (response.data.role as UserRole) || UserRole.STUDENT,
            school: '中山大学',
            email_verified: true,
            created_at: new Date().toISOString()
          } as User
          
          setUser(userData)
        }
        return true
      } else {
        clearToken()
        clearUser()
        return false
      }
    } catch (error) {
      console.error('Check login error:', error)
      clearToken()
      clearUser()
      return false
    }
  }

  // 获取用户完整信息
  const fetchUserProfile = async () => {
    if (!user.value?.id) {
      return
    }

    try {
      const response = await userApi.getUserProfile(user.value.id)
      if (response.data) {
        setUser(response.data)
      }
    } catch (error) {
      console.error('Fetch user profile error:', error)
    }
  }

  // 发送验证码
  const sendVerificationCode = async (email: string, type: 'register' | 'reset_password' | 'change_email' = 'register') => {
    try {
      loading.value = true
      const response = await authApi.sendVerificationCode({ email, type })
      return { 
        success: true, 
        message: '验证码发送成功',
        expires_in: response.data?.expires_in || 300
      }
    } catch (error: any) {
      console.error('Send verification code error:', error)
      return { success: false, message: error.message || '验证码发送失败' }
    } finally {
      loading.value = false
    }
  }

  // 重置密码
  const resetPassword = async (data: {
    token: string
    newPassword: string
  }) => {
    try {
      loading.value = true
      await authApi.resetPassword(data)
      return { success: true, message: '密码重置成功' }
    } catch (error: any) {
      console.error('Reset password error:', error)
      return { success: false, message: error.message || '密码重置失败' }
    } finally {
      loading.value = false
    }
  }

  // 发送重置密码邮件
  const sendResetPasswordEmail = async (email: string) => {
    try {
      loading.value = true
      await authApi.sendVerificationCode({ email, type: 'reset_password' })
      return { success: true, message: '重置密码邮件发送成功' }
    } catch (error: any) {
      console.error('Send reset password email error:', error)
      return { success: false, message: error.message || '发送失败' }
    } finally {
      loading.value = false
    }
  }

  // 修改密码
  const changePassword = async (data: {
    old_password: string
    new_password: string
  }) => {
    try {
      loading.value = true
      await authApi.changePassword(data)
      return { success: true, message: '密码修改成功' }
    } catch (error) {
      console.error('Change password error:', error)
      return { success: false, message: '密码修改失败' }
    } finally {
      loading.value = false
    }
  }

  // 刷新Token
  const refreshToken = async () => {
    try {
      const response = await authApi.refreshToken()
      if (response.data?.token) {
        setToken(response.data.token)
        return true
      }
    } catch (error) {
      console.error('Refresh token error:', error)
      clearToken()
      clearUser()
    }
    return false
  }

  // 初始化时自动检查登录状态
  const initialize = async () => {
    if (token.value) {
      await checkLogin()
    }
  }

  const changeAvatar = async (avatar: FormData) => {
    try {
      const response = await userApi.changeAvatar(avatar)
      if (response.data) {
        setUerAvatar(response.data.avatar_url)
        return { success: true, message: '头像修改成功' , data: response.data }
      }
    } catch (error) {
      console.error('Change avatar error:', error)
      return { success: false, message: '头像修改失败' }
    }
  }

  return {
    // 状态
    token,
    user,
    loading,
    
    // 计算属性
    isAuthenticated,
    isAdmin,
    isTeacher,
    isStudent,
    
    // 方法
    setToken,
    clearToken,
    setUser,
    clearUser,
    login,
    register,
    logout,
    checkLogin,
    fetchUserProfile,
    sendVerificationCode,
    resetPassword,
    sendResetPasswordEmail,
    changePassword,
    refreshToken,
    initialize,
    changeAvatar
  }
})

